package com.jingyuan.biz.event;

import com.jingyuan.biz.event.listener.EventListener;
import com.jingyuan.biz.manager.ClientChannelManager;
import com.jingyuan.common.entity.EventType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 事件注册器
 */
@Service
public class EventManager {
    private Map<Integer,List<EventListener>> listenerMap=new ConcurrentHashMap<>();
    private ThreadPoolExecutor executor;
    @Autowired
    private ClientChannelManager clientChannelManager;

    public EventManager(){
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(512);
        RejectedExecutionHandler policy = new ThreadPoolExecutor.DiscardPolicy();
        this.executor = new ThreadPoolExecutor(5, 20,
                0, TimeUnit.SECONDS,
                queue,
                policy);
    }
    /**
     * 添加注册器
     * @param type 事件类型
     * @param listener 监听器
     */
    public synchronized void addListener(int type,EventListener listener){
        if(listener==null){
            return;
        }
        List<EventListener> listeners=listenerMap.getOrDefault(type,null);
        if(listeners==null){
            listeners=new ArrayList<>();
        }
        listeners.add(listener);
        listenerMap.put(type,listeners);
    }

    /**
     * 事件分发
     * @param eventSource 事件源
     */
    public void dispatch(BaseEvent eventSource){
        if(eventSource==null){
            return;
        }
        List<EventListener> listeners=listenerMap.get(eventSource.getEventType());
        for(EventListener listener:listeners){
            executor.submit(() -> {
                listener.actionListener(eventSource);  //在单独线程中回调，提高性能
            });
        }
    }
}
